<template>
    <view class="container">
        <u-steps class="u-p-t-20" :list="numList" mode="number" :current="4" active-color="#ff5000"></u-steps>
        <view class="item-container">
            <view class="title">店铺信息</view>
            <view class="content">
                <u-form :model="shopInfoForm" ref="shopInfoForm" label-width="210" :error-type="errorType">
                    <u-form-item label="店铺名称：" prop="shop_name" required>
                        <u-input v-model="shopInfoForm.shop_name" placeholder="请输入店铺名称" :maxlength="20" clearable>
                        </u-input>
                    </u-form-item>
                    <u-form-item label="店铺地址：" prop="shop_region" required>
                        <u-input @click="showAddressSelector = true" disabled v-model="shopInfoForm.shop_address"
                            placeholder="请选择店铺地址" clearable></u-input>
                    </u-form-item>
                    <u-form-item label="店铺详细地址：" prop="shop_add" required>
                        <u-input v-model="shopInfoForm.shop_add" placeholder="请输入店铺详细地址" :maxlength="20" clearable>
                        </u-input>
                    </u-form-item>
                    <u-form-item label="经营类目：" prop="shop_img" required>
                        <view class="">
                            <u-checkbox v-model="checkAll" :icon-size="20" @change="handleCheckAllChanged"
                                active-color="#ff5000">全选</u-checkbox>
                            <u-checkbox-group @change="handleCheckedCategorysChange">
                                <u-checkbox v-for="cate in categorys" v-model="cate.checked" :name="cate.id"
                                    :key="cate.id" :icon-size="20" active-color="#ff5000">{{cate.name}}</u-checkbox>
                            </u-checkbox-group>
                        </view>
                    </u-form-item>
                </u-form>
            </view>
        </view>
        <view class="next-btns u-text-center u-p-b-20">
            <u-button class="u-m-r-40" size="mini" @click="handleBackStep">上一步</u-button>
            <u-button size="mini" @click="handleNextStep">提交申请</u-button>
        </view>
        <u-popup v-model="showAddressSelector" mode="bottom" closeable close-icon-size="20" border-radius="20">
            <region-picke @addressSelectorChanged="addressSelectorChanged"
                @closeRegionpicke="showAddressSelector = false" :show="showAddressSelector"></region-picke>
        </u-popup>
    </view>
</template>

<script>
    import * as API_Shop from '@/api/shop'
    import * as API_Goods from '@/api/goods'
    import {
        Foundation,
        RegExp
    } from '@/ui-utils'
    import {
        api
    } from '@/config/config'
    import Cache, {
        Keys
    } from '@/utils/cache.js'
    export default {
        data() {
            const req_rule = (message, trigger) => ({
                required: true,
                message,
                trigger: [trigger || 'blur']
            });
            const len_rule = (min, max) => ({
                min,
                max,
                message: `'长度在 ${min} 到 ${max} 个字符`
            });
            return {
                numList: [{
                    name: '入驻协议'
                }, {
                    name: '基本信息'
                }, {
                    name: '认证信息'
                }, {
                    name: '资质信息'
                }, {
                    name: '店铺信息'
                }],
                shopInfoForm: {
                    shop_name: '',
                    shop_region: '',
                    shop_address: '',
                    shop_add: '',
                    goods_management_category: []
                },
                rules: {
                    shop_name: [req_rule('请输入店铺名称！')],
                    shop_region: [{
                        validator: (rule, value, callback) => {
                            if (!value) {
                                callback(new Error('请选择店铺地址！'))
                            } else {
                                callback()
                            }
                        },
                        trigger: 'blur'
                    }],
                    shop_add: [req_rule('请输入店铺详细地址！')],
                    goods_management_category: [req_rule('请选择经营类目！')]
                },
                errorType: ['toast'],
                action: `${api.buyer}/uploaders`,
                header: {
                    Authorization: Cache.getItem(Keys.accessToken)
                },
                showAddressSelector: false, //地区选择弹出框是否显示
                checkAll: false, // 全选
                categorys: [] //分类
            };
        },
        onLoad() {
            Promise.all([
                API_Shop.getApplyShopInfo(),
                API_Goods.getCategory()
            ]).then(responses => {
                const shopInfo = responses[0]
                const categorys = responses[1]
                const _categorys = shopInfo.goods_management_category && shopInfo.goods_management_category
                    .split(',')
                // 设置店铺信息
                Object.keys(this.shopInfoForm).forEach(key => this.shopInfoForm[key] = shopInfo[key])
                this.shopInfoForm.shop_region = shopInfo.shop_town_id && shopInfo.shop_town_id != 0 ? shopInfo
                    .shop_town_id : shopInfo.shop_county_id
                this.shopInfoForm.shop_address = this.shopInfoForm.shop_region &&
                    `${shopInfo.shop_province || ''} ${shopInfo.shop_city || ''} ${shopInfo.shop_county || ''} ${shopInfo.shop_town || ''}`
                this.shopInfoForm.goods_management_category = []
                if (_categorys) {
                    const _categorys = shopInfo.goods_management_category.split(',')
                    this.shopInfoForm.goods_management_category = _categorys
                    if (_categorys.length !== 0) {
                        if (_categorys.length === categorys.length) {
                            this.checkAll = true
                        }
                    }
                }
                // 设置分类信息
                this.categorys = categorys.map(item => ({
                    id: String(item.category_id),
                    name: item.name,
                    checked: false
                }))
                this.categorys && this.categorys.forEach(item => {
                    if (_categorys && _categorys.toString().indexOf(item.id) > -1) {
                        item.checked = true
                    } else {
                        item.checked = false
                    }
                })
            })
        },
        onReady() {
            this.$refs.shopInfoForm.setRules(this.rules);
        },
        methods: {
            // 店铺所在地
            addressSelectorChanged(object) {
                const obj = {
                    last_id: object[object.length - 1].id,
                    addrs: object.map(key => {
                        return key.local_name
                    }).join(' ')
                }
                this.shopInfoForm.shop_region = obj.last_id
                this.shopInfoForm.shop_address = obj.addrs
            },
            // 经营类目全选框发生改变
            handleCheckAllChanged(checked) {
                this.shopInfoForm.goods_management_category = checked.value ? this.categorys.map(item => item.id) : []
                this.categorys.forEach(item => {
                    if (checked.value) {
                        item.checked = true
                    } else {
                        item.checked = false
                    }
                })
            },
            // 选中的经营类目发生改变
            handleCheckedCategorysChange(value) {
                const checkedCount = value.length
                const categorysCount = this.categorys.length
                this.checkAll = checkedCount === categorysCount
                this.shopInfoForm.goods_management_category = value
            },
            // 上一步
            handleBackStep() {
                uni.navigateBack()
            },
            // 下一步
            handleNextStep() {
                const params = JSON.parse(JSON.stringify(this.shopInfoForm))
                if (!params.goods_management_category.length) {
                    return this.$u.toast('请至少选择一个经营类目')
                }
                params.goods_management_category = params.goods_management_category.join(',')
                this.$refs.shopInfoForm.validate(valid => {
                    if (valid) {
                        API_Shop.applyShopStep(4, params).then(response => {
                            this.$u.route('/pages/shop/apply/success')
                        })
                    }
                })
            }
        }
    }
</script>

<style lang="scss">
    .container {
        height: 100%;
        background-color: #FFFFFF;

        .item-container {
            border-top: 1px dashed #E1E1E1;
            margin: 20rpx 0;

            .title {
                margin: 20rpx 0;
                font-size: 40rpx;
                font-weight: 600;
                text-align: center;
            }

            .content {
                padding: 0 30rpx;
            }

            .licence-range {
                margin-left: 260rpx;
            }
        }
    }

    /deep/ {
        .u-label {
            flex: 0 0 260rpx !important;
        }
    }
</style>
